'use strict';
const dayjs = require("dayjs");
module.exports = app => {
    const { INTEGER, DATE, STRING } = app.Sequelize;
    const City = app.model.define(
        'City',
        {
            id: {type: INTEGER, primaryKey: true, autoIncrement: true},
            pid: INTEGER,
            name: STRING,
            sort: INTEGER,
            status: INTEGER,
            create_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            updated_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('updated_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            }
        },
        {
            tableName: 'city',
            timestamps: true, // 启用时间戳(createdAt, updatedAt)
            updatedAt: 'updated_time', // 不想要 updatedAt
            createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 create_time
        }
    );
    City.associate = function() {
        // 和自己的上级pid关联
        app.model.City.hasMany(app.model.City, { foreignKey: 'pid', sourceKey: 'id', as: 'children' });
        // 关联查询自己的上级
        app.model.City.belongsTo(app.model.City, { foreignKey: 'pid', targetKey: 'id', as: 'parent' });
    };
    return City;
};

